/**
 * kl yy-ds @2021
 */
package com.cxps.server.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.springframework.http.HttpStatus.FORBIDDEN;

/**
 * 网关全局过滤器
 *
 * @author YouCai.Liu
 * @since 2021/11/16
 * ...
 */
@Configuration
public class GatewayGlobalFilter implements GlobalFilter,Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("我是全局过滤器");
        ServerHttpRequest request = exchange.getRequest();
        // 从请求头获取登录标识
        List<String> list = request.getHeaders().get("access_token");
        // 获取请求URL
        String uri = request.getPath().toString();
        /**
         * 如果请求URL包含 /addCar 或者 /collectProduct 并且 请求头的登录标识为空
         * 则重定向到登录页面或返回未登录标识
         */
        if (null == list && uri.contains("/addCar")) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(FORBIDDEN);
            JSONObject message = new JSONObject();
            message.put("status", "2200");
            message.put("data", "未登录");
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
